<?php
namespace app\crud\controller;

use think\Controller;
use think\facade\Env;
use think\Db;

class Index extends Controller {

    public function index() {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改（2006-2018） - 你值得信赖的PHP框架</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
    }

    public function add() {
        if ($this->request->isPost()) {
            // 表单数据

            $ds = DIRECTORY_SEPARATOR;

            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Crud');
            if (true !== $result) {
                $this->error($result);
            }

            $opt = array();
            $opt['module_name'] = strtolower($data['module_name']);
            $opt['model_name'] = ucfirst($data['model_name']);
            $opt['controller_name'] = ucfirst($data['model_name']);
            $opt['validate_name'] = ucfirst($data['model_name']);
            $opt['table_name'] = $opt['module_name'].'_'.humpToLine($data['model_name']);

            $opt['author'] = $data['author'];
            $opt['description'] = $data['description'];
            $opt['menu_id_index'] = $data['menu_id_index'];

            $module_path = Env::get('app_path') . $opt['module_name'] . $ds;

            $view_dir = $module_path . 'view' . $ds . strtolower($opt['model_name']) . $ds;

            $opt['controller_filename'] = $module_path . 'controller' . $ds . $opt['controller_name'] . '.php';
            $opt['model_filename'] = $module_path . 'model' . $ds . $opt['controller_name'] . '.php';
            $opt['validate_filename'] = $module_path . 'validate' . $ds . $opt['controller_name'] . '.php';
            $opt['view_dir'] = $view_dir;
            $opt['view_add_filename'] = $view_dir . 'add.html';
            $opt['view_index_filename'] = $view_dir . 'index.html';
            $opt['view_detail_filename'] = $view_dir . 'detail.html';

            $tpl_path = Env::get('app_path') . 'crud' . $ds . 'tpl' . $ds . $opt['module_name'] . $ds;
            
            $this->build($tpl_path, $opt);

            $this->success('代码生成成功', url('add'));
        } else {
            $maxMenuId = Db::table('__SYS_MENU__')->max('id');
            $this->assign('max_menu_id', $maxMenuId);
            return $this->fetch();
        }
    }

    /**
     * 执行多条
     *
     * @param string $sql
     *            使用;隔开的多条sql
     * @return boolean
     */
    protected function execute_mulsql($sql) {
        $sql = explode(';', $sql);
        if (! $sql)
            return false;
        foreach ($sql as $v) {
            $cur_sql = $v . ';';
            $result = Db::execute($cur_sql);
            if ($result === false)
                return false;
        }
        return true;
    }

    private function build($tpl_path, $opt) {
        $search = array(
            '{__CONTROLLER_DESCRIPTION__}', // 控制器描述
            '{__AUTHOR_DESCRIPTION__}', // 作者描述
            '{__CREATE_TIME__}', // 创建时间
            '{__MODULE_NAME__}', // 创建时间
            '{__CONTROLLER_NAME__}', // 控制器名称
            '{__MODEL_NAME__}', // 模型名称
            '{__TABLEPREX__}', // 表前缀
            '{__TABLE_NAME__}', // 表名称
            '{__TABLE_NAME_VAR__}', // 表常量名称
            '{__TABLE_DESCRIPTION__}', // 表描述
            '{__MENU_ID_INDEX__}', // 表描述
            '{__MODEL_NAME_LOWER__}', // 创建时间
        );
        $replace = array(
            $opt['description'],
            $opt['author'],
            date('Y-m-d H:i:s'),
            $opt['module_name'],
            $opt['controller_name'],
            $opt['model_name'],
            config("database.prefix"),
            $opt['table_name'],
            '__' . strtoupper($opt['table_name']) . '__',
            $opt['description'],
            $opt['menu_id_index'],
            strtolower($opt['model_name']),
        );

        dump($opt);
        if (mkdir($opt['view_dir'])) {

            // 获取模板
            $controller_code = file_get_contents($tpl_path . 'controller.tpl');
            $model_code = file_get_contents($tpl_path . 'model.tpl');
            $validate_code = file_get_contents($tpl_path . 'validate.tpl');

            $view_add_code = file_get_contents($tpl_path . 'view.add.tpl');
            $view_index_code = file_get_contents($tpl_path . 'view.index.tpl');
            $view_detail_code = file_get_contents($tpl_path . 'view.detail.tpl');

            $sql_table_code = file_get_contents($tpl_path . 'sql.table.tpl');

            // 替换标签
            $controller_code = str_replace($search, $replace, $controller_code);
            $model_code = str_replace($search, $replace, $model_code);
            $validate_code = str_replace($search, $replace, $validate_code);

            $view_add_code = str_replace($search, $replace, $view_add_code);
            $view_detail_code = str_replace($search, $replace, $view_detail_code);
            $view_index_code = str_replace($search, $replace, $view_index_code);

            $sql_table_code = str_replace($search, $replace, $sql_table_code);

            // 生成文件以及执行sql
            file_put_contents($opt['controller_filename'], $controller_code) || print_r('生成控制器失败');
            file_put_contents($opt['model_filename'], $model_code) || print_r('生成模型失败');
            file_put_contents($opt['validate_filename'], $validate_code) || print_r('生成验证器失败');

            file_put_contents($opt['view_add_filename'], $view_add_code) || print_r('生成新增/编辑模板失败');
            file_put_contents($opt['view_index_filename'], $view_index_code) || print_r('生成列表模板失败');
            file_put_contents($opt['view_detail_filename'], $view_detail_code) || print_r('生成详情模板失败');
            dump($sql_table_code);

            $this->execute_mulsql($sql_table_code) || print_r('生成数据表失败');
            print_r('代码生成成功');
        }
    }

    private function unlink() {
        foreach ($opt as $key => $value) {
            if (file_exists($value) == true) {
                if (is_file($value)) {
                    unlink($value);
                } else if (is_dir($value)) {
                    rmdir($value);
                }
            }
            ;
        }
    }
}
